package framework;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

import java.nio.charset.StandardCharsets;

/**
 * @Author: DRevelation
 * @Date: 2021/1/4 17:23
 */
public class CuratorDemo {

    /**
     * 重试等待时间
     */
    private static final int BASE_SLEEP_TIME = 1000;
    /**
     * 最大重试次数
     */
    private static final int MAX_RETRIES = 3;

    public static void main(String[] args) {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(BASE_SLEEP_TIME, MAX_RETRIES);
        CuratorFramework zkClient = CuratorFrameworkFactory.builder()
                .retryPolicy(retryPolicy)
                .connectString("121.43.225.108:2181")
                .build();
        zkClient.start();

        try {
            //父节点不存在会报错，推荐第二种方式
//            zkClient.create().withMode(CreateMode.PERSISTENT).forPath("/node1/00001");
            zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT)
                    .forPath("/node2/00001", "hello-curator".getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
